package com.ship.contract.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;
import com.alibaba.excel.read.builder.ExcelReaderSheetBuilder;
import com.ship.common.core.exception.ServiceException;
import com.ship.common.core.utils.FileUtils;
import com.ship.common.core.web.domain.BaseResultCode;
import com.ship.common.core.web.domain.JsonResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/excel" )
public class ExcelRead {

    @GetMapping("/test")
    public JsonResult<Object> test(){
        return JsonResult.success("succeed");
    }

    @PostMapping("/upload")
    @ResponseBody
    public JsonResult<Object> upload(@RequestParam("file") MultipartFile file) {
        FileUtils.checkFileName(file);
        return JsonResult.success("succeed");
    }

    @PostMapping("/read")
    @ResponseBody
    public JsonResult<Object> read(@RequestParam("file") MultipartFile file){
        FileUtils.checkFileName(file);
        try {
            // 从MultipartFile创建ExcelReaderBuilder
            ExcelReaderBuilder excelReaderBuilder = EasyExcel.read(file.getInputStream());

            // 选择要读取的Sheet，并忽略第一行（头部）
            ExcelReaderSheetBuilder sheetBuilder = excelReaderBuilder.sheet().headRowNumber(1);

            // 读取整个Sheet的数据
            List<Map<Integer, Object>> allRows = sheetBuilder.doReadSync();

            // 从allRows中按列提取数据
            Map<String, Map<String, Object>> columnData = new LinkedHashMap<>();
            for (int columnIndex = 1; columnIndex < allRows.get(0).size(); columnIndex++) {
                Map<String, Object> innerData = new LinkedHashMap<>(); // 内层Map，用于存放第0列的值和当前列的值

                for (Map<Integer, Object> row : allRows) {
                    Object firstColumnValue = row.get(0);

                    // 忽略第0列为空的行
                    if (firstColumnValue != null && !firstColumnValue.toString().isEmpty()) {
                        Object columnValue = row.get(columnIndex);
                        innerData.put(firstColumnValue.toString(), (columnValue != null) ? columnValue : "");
                    }
                }

                // 将内层Map作为值，以"Column+当前列"为key，放入外层Map
                columnData.put("Column " + columnIndex, innerData);
            }

            // 将提取的数据以JSON格式返回
            return JsonResult.success(columnData);
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.failed("读取失败");
        }
    }

    @PostMapping("/read2")
    @ResponseBody
    public JsonResult<Object> read2(@RequestParam("file") MultipartFile file){
        FileUtils.checkFileName(file);
        try {
            // 从MultipartFile创建ExcelReaderBuilder
            ExcelReaderBuilder excelReaderBuilder = EasyExcel.read(file.getInputStream());

            // 选择要读取的Sheet，并忽略第一行（头部）
            ExcelReaderSheetBuilder sheetBuilder = excelReaderBuilder.sheet().headRowNumber(1);

            // 读取整个Sheet的数据
            List<Map<Integer, Object>> allRows = sheetBuilder.doReadSync();

            // 从allRows中按列提取数据
            List<Map<String, Object>> columnDataList = new ArrayList<>();
            for (int columnIndex = 2; columnIndex < allRows.get(0).size(); columnIndex++) {
                Map<String, Object> innerData = new LinkedHashMap<>(); // 内层Map，用于存放第0列的值和当前列的值

                for (Map<Integer, Object> row : allRows) {
                    Object firstColumnValue = row.get(0);

                    // 忽略第0列和第1列为空的行
                    if (firstColumnValue != null && !firstColumnValue.toString().isEmpty() &&
                            columnIndex < row.size()) {
                        Object columnValue = row.get(columnIndex);
                        innerData.put(firstColumnValue.toString(), (columnValue != null) ? columnValue : "");
                    }
                }

                // 将内层Map放入List
                columnDataList.add(innerData);
            }

            // 将提取的数据以JSON格式返回
            return JsonResult.success(columnDataList);

        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.failed("读取失败");
        }
    }
}
